LOLMatrix.teamDetail = (function () {


    return {
        //get percent for value
        getPer: function (val, type) {
            var ret = 0;
            var arr = type.split(',');
            ret = (val - arr[0]) / (arr[1] - arr[0]);
            return ret;
        },

        /*
        * 球效果
        * box：传入的球
        * val：选手百分比值
        * worldVal：世界百分比
        * num：数字值----有数值时直接显示数值；
        *
        * */
        curRightAng: 0,
        curLeftAng: 0,
        rightHalfVisible: false,
        oldLetterCls: '',
        angle: function (opt) {
            var def = {
                boxId: null,
                val: 0,
                worldVal: 1,
                num: false,
                rank: 'D',
                type: '',
                text: '',
                tag:'t1',//默认为第一种计算方式
                textBoxId: ''
            };

            opt = $.extend(true, def, opt);
            if (!opt.boxId) { return false; }

            //UI 元素处理
            var box = $(opt.boxId);
            var
                me = this,
                rightHalf = $(".right-half", box),
                rotateRight = $(".right", box),
                rotateLeft = $(".left", box),

                percent = $(".cur", box),
                worldPercent = $(".world", box),
                letter = $(".letter", box);

            if (box.length <= 0 || rightHalf.length <= 0 || rotateRight.length <= 0 || rotateLeft.length <= 0) {
                return false;
            }






            //获取角度值
            function getAngleVal(val) {
                val = val || 0;
                if (val > 1) val = 1;
                return Math.ceil(360 * val);
            }


            //设置个人百分比位置
            function setPercentPos(percent, angleVal, r) {

                var percentPos = { top: 0, left: 0 };
                // var r=parseInt(box.width())/2;
                var polar = { len: r + 10, p: angleVal };
                polar.p = 2 * Math.PI / 360 * polar.p;


                percentPos.left = parseInt(polar.len * Math.sin(polar.p)) + r;
                percentPos.top = r - parseInt(polar.len * Math.cos(polar.p));


                //除去百分比本身的宽与高；
                percentPos.left -= parseInt(percent.width() / 2);
                percentPos.top -= parseInt(percent.height() / 2);


                //位置向外移动距离 修正效果；
                if (percentPos.left > 0) {
                    percentPos.left += 5;
                } else {
                    percentPos.left -= 10;
                }


                // console.log(percentPos);
                percent.css(percentPos);


            }

            //更新等级
            function updateLevel(str) {

                str = str || 'd';
                str = str.toLowerCase();
                //等级处理
                var levelCls = 'letter-' + str;

                if (letter.length > 0) {
                    if (me.oldLetterCls) {
                        letter.removeClass(me.oldLetterCls).hide();
                    }
                    letter.addClass(levelCls).fadeIn(500);
                    me.oldLetterCls = levelCls;
                }

            }

            //更新数值--如果有的话
            function updateNumber() {
                //数值处理
                var number = $(".number", box);
                var str = number.attr('data-ball').split(',');

                if (number.length > 0) {
                    number.html(str[1]);
                }

                return str[0];
            }


            //更新textBoxId内的内容
            function updateTextBoxCont(textBox, val, worldVal) {
                var p = $(".person-val", textBox),
                    w = $(".world-val", textBox),
                    pTitle = $(".person-title", textBox);

                if (p.length > 0) {
                    p.html(val);
                    pTitle.html(opt.text);
                }

                if (w.length > 0) {
                    w.html(worldVal);
                }
            }








            //显示右半边圆
            function showRightHalf() {
                rotateRight.hide();
                rightHalf.show();
            };

            //隐藏右半边圆
            function hideRightHalf() {
                rotateRight.show();
                rightHalf.hide();
            };

            //显示个人百分比
            function showPersonPercent() {
                if (percent.length > 0) { percent.fadeIn(50); }
            }

            function hidePersonPercent() {
                if (percent.length > 0) { percent.hide(); }
            }

            //转圈圈
            function ani(angleVal) {
                hidePersonPercent();

                if (angleVal >= 0 && angleVal <= 180) {

                    if (me.curLeftAng > 0) {
                        rotateLeft.transition({ transform: "rotate(" + (0) + "deg)" }, 'fast', "ease-in", function () {
                            me.curLeftAng = 0;
                            hideRightHalf();
                            rotateRight.transition({ transform: "rotate(" + angleVal + "deg)" }, 'fast', "ease-out", function () {
                                me.curRightAng = angleVal;
                                showPersonPercent();
                            });
                        });
                    } else {
                        rotateRight.transition({ transform: "rotate(" + angleVal + "deg)" }, 'fast', "ease-in", function () {
                            hideRightHalf();
                            me.curRightAng = angleVal;
                            me.curLeftAng = 0;
                            showPersonPercent();
                        });
                    }
                } else if (angleVal > 180 && angleVal <= 360) {
                    rotateRight.transition({ transform: "rotate(" + 180 + "deg)" }, 'fast', "ease-in", function () {
                        showRightHalf();
                        me.curRightAng = 180;
                        rotateLeft.transition({ transform: "rotate(" + (angleVal - 180) + "deg)" }, 'fast', "ease-out", function () {
                            me.curLeftAng = angleVal - 180;
                            showPersonPercent();
                        });
                    });
                }

            }



            //开始处理----------------------------------------------------
            var angleVal = 0;
            var val = 0;
            var valText = '';
            var worldValText = '';

            //如果有数值，
            if (opt.num) {
                angleVal = getAngleVal(updateNumber());
            } else {

                switch (opt.tag) {
                    case "t1":
                        opt.val = Math.round(opt.val, 0);
                        opt.worldVal = Math.round(opt.worldVal, 0);
                        val = opt.val / (opt.worldVal * 2);
                        angleVal = getAngleVal(val);
                        valText = opt.val + "%";
                        worldValText = opt.worldVal + "%";
                        break;
                    case "t2":
                        val = me.getPer(opt.val, opt.type);
                        angleVal = getAngleVal(val.toFixed(2));
                        valText = parseFloat(opt.val).toFixed(2);
                        worldValText = parseFloat(opt.worldVal).toFixed(2);
                        break;
                    case "t3":
                        val = opt.val / (opt.worldVal * 2);
                        angleVal = getAngleVal(val.toFixed(2));
                        valText = parseFloat(opt.val).toFixed(2);
                        worldValText = parseFloat(opt.worldVal).toFixed(2);
                        break;
                }

                //更新，并设置个人百分比位置
                percent.html(valText);
                worldPercent.html(worldValText);
                updateTextBoxCont($(opt.textBoxId), valText, worldValText);
                setPercentPos(percent, angleVal, parseInt(box.width()) / 2);

                updateLevel(opt.rank);
            }

            ani(angleVal);
        },


        //圈圈切换效果
        ballChange: function () {
            var
                typeBox = $(".type"), typeList = $("li", typeBox),
                scores = $("#scores"), scoresList = $("li", scores),
                cls = 'cur',
                self = this;
            if (typeList.length <= 0 || scoresList.length <= 0) { return; }

            //获取局数
            function getScores() {
                var num = 10;
                $.each(scoresList, function (index, item) {
                    if ($(item).hasClass('cur')) {
                        num = $(item).attr("data-num");
                    }
                });
                return num;
            };

            //获取当前字段的数据
            function getData(num) {
                var data = '1,1,D';
                $.each(typeList, function (index, item) {
                    if ($(item).hasClass('cur')) {
                        data = $(item).attr("data-" + num);
                    }
                });
                return data;
            }



            //参数
            var param = {
                boxId: '#levelBall',
                val: 0.5,
                worldVal: 0.5,
                rank:'D',
                textBoxId: "#percentBox"
            };



            //字段
            typeList.bind("click", function () {
                var me = $(this);
                var num = getScores();
                me.addClass(cls).siblings().removeClass(cls);

                var data = me.attr('data-' + num).split(",");
                param.val = data[0];
                param.worldVal = data[1];
                param.rank = data[2];
                param.type = me.attr('data-type');
                param.text = me.text();
                param.tag = me.attr('data-tag');
                self.angle(param);
            });

            //局数
            scoresList.bind("click", function () {
                var me = $(this);
                me.addClass(cls).siblings().removeClass(cls);

                var data = getData(me.attr("data-num")).split(",");
                param.val = data[0];
                param.worldVal = data[1];
                param.rank = data[2];

                self.angle(param);
            });


            //首次加载
            typeList.eq(0).click();


        },


        //滚动条
        scrollPanel: function () {
            //相关新闻
            if ($(".row5-box").length > 0) {
                $(".row5-box").mCustomScrollbar({
                    theme: "light",
                    scrollButtons: { enable: true }
                });
            };

            //转会记录
            if ($(".row6-box").length > 0) {
                $(".row6-box").mCustomScrollbar({
                    theme: "light",
                    scrollButtons: { enable: true }
                });
            };

            //team rank
            if ($(".detail-row2").length > 0) {
                $(".detail-row2").mCustomScrollbar({
                    theme: "light",
                    scrollButtons: { enable: true }
                });
            }

        },





        //生成一个指定范围的随机数字 min,max
        getRangeRndNum: function (min, max) {
            switch (arguments.length) {
                case 1: return parseInt(Math.random() * min + 1);
                case 2: return parseInt(Math.random() * (max - min + 1) + min);
                default: return 0;
            }
        },


        //长度bar切换
        bar: function (tabBox, liBox) {

            if (!tabBox || !liBox) { return false; }
            var me = this;

            var lis = $("li", liBox), tabs = $("li", tabBox);
            //生成指定长度的数组数据

            var createData=function(attribute) {
                var ret = [];
                var barWidth = 332;
                var defaultBarWidth = 2;
                $.each(lis, function (index, item) {
                    var li = $(item);
                    var data = li.attr(attribute).split(",");
                    var type = li.attr('data-type');
                    var tag = li.attr('data-tag');
                    var obj = {
                        rank: data[1],
                        num: (data[0] * 1).toFixed(1)
                    }
                    if (tag === "t1") {
                        obj.percent = Math.round(data[0] * 1);
                        obj.width = obj.percent * 0.01 * barWidth || defaultBarWidth;
                        if (type) {
                            obj.width = me.getPer(obj.percent, type) * barWidth;
                        }
                    } else {
                        obj.width = me.getPer(obj.num, type) * barWidth;
                    }
                    ret.push(obj);
                });

                return ret;
            }

            var data = [
                createData('data-10'),
                createData('data-25'),
                createData('data-40')
            ];


            //动态更新bar
            function animate(bars, data) {
                $.each(bars, function (i, o) {
                    var item = $(o),
                        bar = $("span", item),
                        text = $("i", item),
                        column3 = $(".column3", item),
                        tag = item.attr('data-tag');

                    if (tag === 't1') {
                        text.html(data[i].percent + '%');
                    } else {
                        text.html(data[i].num);
                    }

                    column3.html(data[i].rank);
                    bar.animate({ width: data[i].width }, "slow");
                });
            }

            //首次加载
            animate(lis, data[0]);

            //切换
            tabBox.undelegate("click");
            tabBox.delegate("li", "click", function () {
                $(this).addClass("cur").siblings().removeClass("cur");
                var index = tabs.index(this);
                animate(lis, data[index]);
            });

        },


        // 弹窗
        dialogCtrl: function () {
            var dialog = LOLMatrix.common.dialog;
            var me = this;

            //队伍比较
            var btnTeam = $(".btn-team");
            btnTeam.bind("click", function (e) {
                e.preventDefault();
                if (dialog) {
                    dialog.showDialog($('div.team-dialog'));
                    $("select.dropdown", this).easyDropDown();
                }
            });


            //队伍总览
            var btnAll = $(".team-detail-all");
            btnAll.bind("click", function (e) {
                e.preventDefault();
                if (dialog) {
                    dialog.showDialog($('div.pandect-dialog'));

                    //滚动条
                    $(".pandect-box").mCustomScrollbar({
                        theme: "light-2",
                        scrollButtons: { enable: true }
                    });

                    //数据切换
                    me.bar($(".tabs"), $(".bars"));

                    //ban /pick
                    //参数


                    var param1 = { boxId: '#ball1', num: 1,},
                    param2 = { boxId: '#ball2',  num: 1 },
                    param3 = { boxId: '#ball3',  num: 1 };
                    me.angle(param1);
                    me.angle(param2);
                    me.angle(param3);
                }
            });

            //  btnAll.click();
        },


        //队伍成员
        teamMan: function () {
            if ($(".team-man li").length > 5) {
                $('.team-man').slick({
                    slidesToShow: 5,
                    slidesToScroll: 1,
                    accessibility: false,
                    draggable: false
                });
            }
        }

    }


})();




$(function () {
    var teamDetail = LOLMatrix.teamDetail;
    teamDetail.scrollPanel();
    teamDetail.dialogCtrl();

    //新加
    teamDetail.ballChange();
    teamDetail.teamMan();






    //图表部分
    var defTextStyle = { fontFamily: "Arial,Microsoft YaHei", fontSize: 10, fontWeight: 'lighter' };

    //线条图参数
    var line = {
        lineOpts: {
            //提示
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    lineStyle: {
                        color: '#243f53',
                        width: 1,
                        shadowBlur: 0
                    }
                },
                formatter: "{c}"
            },
            //图表标题
            title: {
                text: $('#teamTrend').val(), x: 55, y: 0,
                textStyle: { color: '#ffffff', fontSize: 14, fontFamily: 'Microsoft YaHei', fontWeight: 'lighter' }
            },
            //图表大小及边距设置
            grid: { x: 50, y: 30, x2: 0, y2: 30, borderWidth: 0 },

            //x轴
            xAxis: {
                //坐标轴线
                axisLine: { lineStyle: { color: '#243f53', width: 1, type: 'solid' } },
                //  boundaryGap: false,
                //网格线
                splitLine: { show: false },
                boundaryGap: true,
                //坐标轴文本
                axisLabel: { show: false },

                //坐标轴刻度
                axisTick: { show: false },

                //坐标轴类型
                type: 'category',

                //坐标轴名称与样式
                name: '局数',


                //x轴刻度数据
                data: []

            },

            //y轴
            yAxis: {

                //网格线
                splitLine: { lineStyle: { color: '#243f53' } },
                //splitLine: {show: false},

                axisLine: { lineStyle: { color: '#243f53', width: 1, type: 'solid' } },
                name: '',
                nameTextStyle: { color: '#ffffff', fontFamily: 'Microsoft YaHei' },
                axisLabel: { textStyle: { color: '#ffffff' } },



                type: 'value',
                // splitNumber: 5,
                scale: true,
                //y轴刻度数据
                min: 1800, max: 2050

            },

            series: [
                {
                    name: '',
                    type: 'line',
                    showAllSymbol: true,
                    itemStyle: {
                        normal: {
                            lineStyle: {
                                shadowColor: 'rgba(0,0,0,0.4)',
                                border: 1
                            },
                            barBorderColor: '#7ed2f5',
                            color: '#7ed2f5',
                        },
                        emphasis: {
                            lineStyle: {
                                shadowColor: 'rgba(0,0,0,0.4)'
                            },
                            barBorderColor: '#7ed2f5',
                            color: '#7ed2f5'
                        }
                    },
                    data: []
                }
            ]
        },
        createLine: function (dom) {
            return echarts.init(dom);
        }
    };

    //线条图
    var lineBox = $(".lineZone"),
        lineItems = $('#lineNumber li');
    if (lineBox.length > 0 && lineItems.length > 0) {

        //获取数据
        function getLineData(li) {
            var isLabel = true;

            if (li.attr('data-num') * 1 > 10) {
                isLabel = false;
            }


            var data = [], strArr = '';
            var label = {
                normal: {
                    color: '#ffffff',
                    barBorderRadius: 5,
                    borderRadius: 5,
                    label: {
                        show: isLabel,
                        textStyle: defTextStyle
                    }
                },
                emphasis: {
                    color: '#ffffff',
                    barBorderRadius: 4,
                    label: { textStyle: defTextStyle }
                }
            };
            strArr = li.attr('data-str');

            if (strArr) {
                strArr = strArr.split(",");
                strArr = strArr.reverse();

                $.each(strArr, function (index, item) {
                    data.push({ value: item, itemStyle: label });
                });
            }


            return data;
        }

        //获取x轴数据
        function getXData(li) {
            var data = [];
            var num = li.attr("data-num") * 1;
            for (var i = 1; i <= num; i++) {
                data.push(i);
            }
            return data;
        }

        //获取y轴最大值与最小值
        function getRange(data, diff) {
            var ret = { min: 0, max: 0 },
                numArr = [],
                diff = diff || 10;
            $.each(data, function (index, item) {
                numArr.push(item.value);
            });

            ret.max = Math.max.apply(null, numArr);
            ret.min = Math.min.apply(null, numArr) - diff;
            // console.log(ret);

            return ret;
        }






        //首次运行时
        // set opts
        var opts = $.extend({}, line.lineOpts);
        opts.xAxis.data = getXData(lineItems.eq(0));
        var myData = getLineData(lineItems.eq(0));
        var lineChart;
        if (myData.length > 0) {
            opts.series[0].data = myData;

            var ret = getRange(myData);
            opts.yAxis.min = ret.min;
            opts.yAxis.max = undefined;


            // create chart
            lineChart = line.createLine(lineBox[0]);
            lineChart.setOption(opts);
        }



        //click load
        lineItems.bind("click", function () {
            var curRow = $(this);
            curRow.addClass("cur").siblings().removeClass('cur');

            var opts = $.extend({}, line.lineOpts);
            opts.xAxis.data = getXData(curRow);
            opts.series[0].data=getLineData(curRow);

            var ret = getRange(getLineData(curRow));
            opts.yAxis.min = ret.min;
            opts.yAxis.max = undefined;

            if (lineChart) {
                lineChart.clear();
                lineChart.setOption(opts);
            }
        });
    }
});
